/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.gui;

import it.polimi.deib.se2.meteocal.business.boundary.LocationManager;
import it.polimi.deib.se2.meteocal.business.control.DataWeatherImport;
import it.polimi.deib.se2.meteocal.business.control.WeatherCodeConverter;
import it.polimi.deib.se2.meteocal.business.entity.Location;
import java.io.IOException;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import org.json.JSONException;

@Named
@RequestScoped
public class LocationBean {
    
    @EJB
            LocationManager lm;
    
    public LocationBean() {
    }
    
    //it attached weather only to the location specified in days specified to speed up the process during creation
    public void attachWeatherToSingleLocation(Location loc) throws JSONException, IOException{
        
        DataWeatherImport dwi = new DataWeatherImport();
        StringBuilder weatherForecast = new StringBuilder();
        int codes[] = new int[16];
        try {
            codes = dwi.forecastWeatherAtCity(loc.getLocName());
        } catch (JSONException | IOException ex) {
            for(int i=0; i<16; i++){
                codes[i] = -1;
            }            }
        for(int i=0; i<16; i++){
            String meteo = WeatherCodeConverter.convertCode(codes[i]);
            weatherForecast.append(meteo);
            if(i!=15)
                weatherForecast.append(",");

        }

        loc.setWeather(weatherForecast.toString());
        lm.update(loc);
    }
}